package com.chinasofti.SSM.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.jboss.logging.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.chinasofti.SSM.pojo.Role;
import com.chinasofti.SSM.pojo.User;
import com.chinasofti.SSM.service.role.RoleService;
import com.chinasofti.SSM.service.user.UserService;
import com.chinasofti.SSM.tools.Constants;
import com.chinasofti.SSM.tools.PageSupport;
import com.mysql.jdbc.StringUtils;




@Controller
@RequestMapping("/user")
public class UserController{
	@Resource
	private UserService userService;
    @Resource
	private RoleService roleService;
    private Logger log=Logger.getLogger(UserController.class);
    
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	
	@RequestMapping("/queryUserList")
	public String queryUserList(@RequestParam(value="userName",required=false)String queryUserName,
			@RequestParam(value="userRole",required=false)String temp,
			@RequestParam(value="pageIndex",required=false)String pageIndex,
			HttpServletRequest request) {
		//查询用户列表
		int queryUserRole = 0;
		List<User> userList = null;
		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
    	int currentPageNo = 1;
		/**
		 * http://localhost:8090/SMBMS/userlist.do
		 * ----queryUserName --NULL
		 * http://localhost:8090/SMBMS/userlist.do?queryname=
		 * --queryUserName ---""
		 */
		System.out.println("queryUserName servlet--------"+queryUserName);  
		System.out.println("queryUserRole servlet--------"+queryUserRole);  
		System.out.println("query pageIndex--------- > " + pageIndex);
		if(queryUserName == null){
			queryUserName = "";
		}
		if(temp != null && !temp.equals("")){
			queryUserRole = Integer.parseInt(temp);
		}
		
    	if(pageIndex != null){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
    			//response.sendRedirect("error.jsp");
    			return "user/error";
    		}
    	}	
    	//总数量（表）	
    	int totalCount	= userService.getUserCount(queryUserName,queryUserRole);
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	
    	int totalPageCount = pages.getTotalPageCount();
    	
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
		
		userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize);
		request.setAttribute("userList", userList);
		List<Role> roleList = null;
		roleList = roleService.getRoleList();
		request.setAttribute("roleList", roleList);
		request.setAttribute("queryUserName", queryUserName);
		request.setAttribute("queryUserRole", queryUserRole);
		request.setAttribute("totalPageCount", totalPageCount);
		request.setAttribute("totalCount", totalCount);
		request.setAttribute("currentPageNo", currentPageNo);
		//request.getRequestDispatcher("userlist.jsp").forward(request, response);
		return "userlist";
	}
	
	@RequestMapping(value="/useradd2",method=RequestMethod.GET)
	public String useradd2(@ModelAttribute User user) {
		
		return "useradd";
	}
	
	@RequestMapping(value="/useradd2",method=RequestMethod.POST)
	public String useradd2(@Valid User user,BindingResult result,HttpSession session) {
		if(result.hasErrors()) {
			return "useradd";
		}
		try {
			System.out.println("add()================");
			user.setCreationDate(new Date());
			user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
			
			if(userService.add(user)){
				//response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
				return "redirect:/user/queryUserList";
			}else{
				//request.getRequestDispatcher("useradd.jsp").forward(request, response);
				return "useradd";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return "useradd";
	}
	
	/**
	 * 多文件上传方式 -2 单独入参
	 * @param user
	 * @param session
	 * @param request
	 * @param attachs
	 * @return
	 */
	@RequestMapping(value="/useraddsave.html",method=RequestMethod.POST)
	public String addUserSave(User user,HttpSession session,HttpServletRequest request,
							 @RequestParam(value ="a_idPicPath", required = false) MultipartFile idPicFile,
							 @RequestParam(value="a_workPicPath",required=false)MultipartFile workPicFile){
		String idPicPath = null;
		String workPicPath = null;
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles"); 
		log.info("uploadFile path ============== > "+path);
		
		//判断文件是否为空(证件照)
		if(!idPicFile.isEmpty()){
			String oldFileName = idPicFile.getOriginalFilename();//原文件名
			log.info("uploadFile oldFileName ============== > "+oldFileName);
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀     
	        log.debug("uploadFile prefix============> " + prefix);
			int filesize = 500000;
			log.debug("uploadFile size============> " + idPicFile.getSize());
	        if(idPicFile.getSize() >  filesize){//上传大小不得超过 500k
            	request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
	        	return "useradd";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
            		|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
            	String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";  
                log.debug("new fileName======== " + idPicFile.getName());
                File targetFile = new File(path, fileName);  
                if(!targetFile.exists()){  
                    targetFile.mkdirs();  
                }  
                //保存  
                try {  
                	idPicFile.transferTo(targetFile);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "useradd";
                }  
                idPicPath = path+File.separator+fileName;
                //idPicPath = request.getContextPath()+"/statics/uploadfiles/"+fileName;
            }else{
            	request.setAttribute("uploadFileError", " * 上传图片格式不正确");
            	return "useradd";
            }
		}
		
		//判断文件是否为空(工作证照)
		if(!workPicFile.isEmpty()){
			String oldFileName = workPicFile.getOriginalFilename();//原文件名
			log.info("uploadFile oldFileName ============== > "+oldFileName);
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀     
	        log.debug("uploadFile prefix============> " + prefix);
			int filesize = 500000;
			log.debug("uploadFile size============> " + workPicFile.getSize());
	        if(workPicFile.getSize() >  filesize){//上传大小不得超过 500k
            	request.setAttribute("uploadWpError", " * 上传大小不得超过 500k");
	        	return "useradd";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
            		|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
            	String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";  
                log.debug("new fileName======== " + workPicFile.getName());
                File targetFile = new File(path, fileName);  
                if(!targetFile.exists()){  
                    targetFile.mkdirs();  
                }  
                //保存  
                try {  
                	workPicFile.transferTo(targetFile);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                    request.setAttribute("uploadWpError", " * 上传失败！");
                    return "useradd";
                }  
                workPicPath=path+File.separator+fileName;
                //workPicPath = request.getContextPath()+"/statics/uploadfiles/"+fileName;
            }else{
            	request.setAttribute("uploadWpError", " * 上传图片格式不正确");
            	return "useradd";
            }
		}
		
		user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		user.setIdPicPath(idPicPath);
		user.setWorkPicPath(workPicPath);
		if(userService.add(user)){
			return "redirect:/user/queryUserList";
		}
		return "useradd";
	}
	
	/**
	 * 同名验证
	 * @param userCode
	 * @return
	 */
	@RequestMapping("/userCodeIsExit")
	@ResponseBody
	public Object userCodeIsExit(String userCode){
		//判断用户账号是否可用	
				HashMap<String, String> resultMap = new HashMap<String, String>();
				if(StringUtils.isNullOrEmpty(userCode)){
					//userCode == null || userCode.equals("")
					resultMap.put("userCode", "exist");
				}else{
					User user = userService.selectUserCodeExist(userCode);
					if(null != user){
						resultMap.put("userCode","exist");
					}else{
						resultMap.put("userCode", "notexist");
					}
				}
				
			//把resultMap转为json字符串以json的形式输出		
			return JSONArray.toJSONString(resultMap);
	}
	
	@RequestMapping("/getrolelist")
	   @ResponseBody
	   public Object getrolelist() {
		    List<Role> roleList = null;
			roleList = roleService.getRoleList();
			//把roleList转换成json对象输出	
			return JSONArray.toJSONString(roleList);   
	   }
	
	@RequestMapping("/pwdmodify")
	public String pwdmodify(){
		
		return "pwdmodify";
	}
	
	@RequestMapping("/pwdmodify2")
	@ResponseBody
	public Object pwdmodify(String oldpassword,HttpSession session){
		Object o = session.getAttribute(Constants.USER_SESSION);
		Map<String, String> resultMap = new HashMap<String, String>();
		if(null == o ){//session过期
			resultMap.put("result", "sessionerror");
		}else if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
			resultMap.put("result", "error");
		}else{
			String sessionPwd = ((User)o).getUserPassword();
			if(oldpassword.equals(sessionPwd)){
				resultMap.put("result", "true");
			}else{//旧密码输入不正确
				resultMap.put("result", "false");
			}
		}	
		//把resultMap转为json字符串以json的形式输出
		return JSONArray.toJSONString(resultMap);	
	}
	
	@RequestMapping("/updatePwd")
	public String updatePwd(String newpassword,HttpSession session,HttpServletRequest request) {

	Object o = session.getAttribute(Constants.USER_SESSION);
	boolean flag = false;
	if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
		flag = userService.updatePwd(((User)o).getId(),newpassword);
		if(flag){
			request.setAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录！");
			session.removeAttribute(Constants.USER_SESSION);//session注销
		}else{
			request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
		}
	}else{
		request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
	}
	//request.getRequestDispatcher("pwdmodify.jsp").forward(request, response);
	   return "login";
   }
	
	@RequestMapping("/delUser")
	   @ResponseBody
	   public Object delUser(String id) {
			Integer delId = 0;
			try{
				delId = Integer.parseInt(id);
			}catch (Exception e) {
				// TODO: handle exception
				delId = 0;
			}
			HashMap<String, String> resultMap = new HashMap<String, String>();
			if(delId <= 0){
				resultMap.put("delResult", "notexist");
			}else{
				if(userService.deleteUserById(delId)){
					resultMap.put("delResult", "true");
				}else{
					resultMap.put("delResult", "false");
				}
			}	
			//把resultMap转换成json对象输出
			return JSONArray.toJSONString(resultMap);   
	  }
	
	@RequestMapping("/getUserById")
	public String getUserById(@RequestParam(value="uid",required=false)String id,HttpServletRequest request){
		
		if(!StringUtils.isNullOrEmpty(id)){
			//调用后台方法得到user对象
			User user = userService.getUserById(id);
			request.setAttribute("user", user);
		}
		return "usermodify";
	}
	
	@RequestMapping("/modifyUserSave")
	public String modifyUserSave(User user,HttpSession session){
		
		user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setModifyDate(new Date());		
		if(userService.modify(user)){
			return "redirect:/user/queryUserList";
		}else{
			return "usermodify";
		}
	}
	
	/**
	 * 使用FastJsonHttpMessageConverter 来解决返回日期类型
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/view")
	@ResponseBody
	public Object view(String id) {
		User user = null;
		if(!StringUtils.isNullOrEmpty(id)){
			//调用后台方法得到user对象
			user = userService.getUserById(id);
			return user;
		} else {
			return "nodata";
		}
	}
}
